import axios from 'axios'

// 创建 axios 实例
const api = axios.create({
    baseURL: 'http://localhost:3000/api',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器 - 添加认证 token
api.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器 - 处理错误
api.interceptors.response.use(
    (response) => response.data,
    (error) => {
        if (error.response?.status === 401) {
            localStorage.removeItem('token')
            localStorage.removeItem('currentUser')
            window.location.href = '/'
        }
        return Promise.reject(error)
    }
)

// API 接口定义
export const apiService = {
    // 统计数据
    getDashboardStats: () => api.get('/dashboard/stats'),

    // 图表数据
    getChartData: (period: string) => api.get(`/charts/sales?period=${period}`),
    getOrderData: (period: string) => api.get(`/charts/orders?period=${period}`),

    // 商品管理
    getProducts: (page = 1, limit = 10) => api.get(`/products?page=${page}&limit=${limit}`),
    createProduct: (data: any) => api.post('/products', data),
    updateProduct: (id: number, data: any) => api.put(`/products/${id}`, data),
    deleteProduct: (id: number) => api.delete(`/products/${id}`),

    // 用户管理
    getUsers: (page = 1, limit = 10) => api.get(`/users?page=${page}&limit=${limit}`),
    createUser: (data: any) => api.post('/users', data),
    updateUser: (id: number, data: any) => api.put(`/users/${id}`, data),
    deleteUser: (id: number) => api.delete(`/users/${id}`),

    // 实时数据
    getRealtimeData: () => api.get('/realtime'),

    // 系统信息
    getSystemInfo: () => api.get('/system/info')
}

export default apiService